package com.degani.pdf;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

public  class CellCoordinate{

	private static Logger logger = Logger.getLogger(CellCoordinate.class);	
	
	private int row;
	private int column;

	public CellCoordinate(int row, int column) {
		this.row = row;
		this.column = column;
	}
	public int getRow() {
		return row;
	}
	public void setRow(int row) {
		this.row = row;
	}
	public int getColumn() {
		return column;
	}
	public void setColumn(int column) {
		this.column = column;
	}
	
	private static Pattern addressPattern = Pattern.compile("([A-Z]+)(\\d+)");
	
    private static int GetExcelColumnIndex(String columnName)
    {
        int mult = 1;
        int index = 0;
        for (int i = columnName.length(); i > 0; i--)
        {
            index += mult * (columnName.charAt(i - 1) - 'A' + 1);
            mult *= 26;
        }
        return index;
    }	
	
	public static CellCoordinate fromString(String cellAddress){
		// remove any $ signs
		cellAddress = cellAddress.trim().replaceAll("$", "").toUpperCase();
		
		// split the row and column
		Matcher m = addressPattern.matcher(cellAddress);
		if(m.matches()){
			String column = m.group(1);
			String row = m.group(2);
			return new CellCoordinate(Integer.parseInt(row) - 1, 
					GetExcelColumnIndex(column) - 1);
		} else {
			logger.error(String.format("Could not understand address: %s", cellAddress));
			return null;
		}
	}
}
